package com.example.spider.provider.m3u8.handler;

import com.example.spider.provider.m3u8.task.M3u8TsTask;
import com.example.spider.task.SpiderResultHandler;
import com.example.spider.util.PathUtil;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.shoulder.batch.progress.BatchProgressCache;
import org.shoulder.crypto.symmetric.SymmetricCipher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.file.Path;
import java.security.Security;

/**
 * 保存TS片段
 *
 * @author lym
 */
@Slf4j
@Component
public class M3u8TsHandler implements SpiderResultHandler<M3u8TsTask, byte[]> {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    @Autowired
    private SymmetricCipher symmetricCipher;

    @Autowired
    private BatchProgressCache progressCache;

    /**
     * handle
     */
    @Override
    public void handle(M3u8TsTask task, byte[] tsPart) {
        log.debug("prepare handing Ts:{}", task.getUrl());
        // 解密
        byte[] decrypted = task.getTsPart().getKey().decrypt(tsPart);

        // 确保存在
        Path path = Path.of(task.getTsPart().getFilePath());
        // 覆盖写入
        PathUtil.writeWithTransaction(decrypted, path);

        log.debug("finished write Ts:{}", path);
        // 标记已经完成 无需重试
        progressCache.getProgress(task.getProgressId()).finishPart(task.getTsPart().getPartIndex());

        // 失败不计入，否则合并可能出错
//        task.getCountDownLatch().countDown();
    }
}
